//
//  HomeViewController.swift
//  MT
//
//  Created by ooops on 2019/7/18.
//  Copyright © 2019年 张强. All rights reserved.
//

import UIKit
/// 网络、通用
import MTCategory

import Moya
import Result
import RxSwift
import RxCocoa
/// 其它
import YPNavigationBarTransition
import MJRefresh
import JXPagingView
import JXCategoryView
import CWLateralSlide
import JXSegmentedView

class MineViewController: BaseViewController {
    lazy var pagingView: JXPagingView = preferredPagingView()
    lazy var headerView: MineHeaderView = preferredTableHeaderView()
    let dataSource: JXSegmentedTitleDataSource = JXSegmentedTitleDataSource()
    lazy var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: CGFloat(headerInSectionHeight)))
    //var titles = ["最富俱乐部", "最新俱乐部"]
    var headerInSectionHeight: Int = 42
    var tableHeaderViewHeight: Int {
        get {
            return isSelf ? 437 : 220
        }
    }
    /// 控制器
    var controllers: [UIViewController] = []
    /// 个人简介 Controller
    var profileDetailController: MineProfileDetailViewController?
    /// 动态 Controller
    var publishListController: MinePublishListViewController?
    
    typealias dismissClosure = () -> Swift.Void
    
    private var completeClosure: dismissClosure?
    
    /// 个人资料模型
    var infoModel: MineInfoModel? {
        didSet {
            guard let model = infoModel else { return }
            if model.vipState == 1 {
                if model.vipType == 1 {
                    vipButton?.setImage(UIImage(named: "vipYellow"), for: .normal)
                    vipRightBarBtn?.isEnabled = false
                } else if model.vipType == 2 {
                    vipButton?.setImage(UIImage(named: "vipBlue"), for: .normal)
                    vipRightBarBtn?.isEnabled = false
                } else {
                    vipButton?.setImage(UIImage(named: "vip_apply"), for: .normal)
                    vipRightBarBtn?.isEnabled = true
                }
            } else if model.vipState == 2 {
                vipButton?.setImage(UIImage(named: "vip_gray"), for: .normal)
                vipRightBarBtn?.isEnabled = false
            } else if model.vipState == 0 {
                vipButton?.setImage(UIImage(named: "vip_apply"), for: .normal)
                vipRightBarBtn?.isEnabled = true
            }
        }
    }
    
    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    /// PublishApi
    private lazy var publish_provider: MTProvider<PublishApi> = {
        return MTProvider<PublishApi>(plugins: [])
    }()
    /// UserApi
    private lazy var user_provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    /// Vip 按钮
    var vipButton: UIButton?
    var vipRightBarBtn: UIBarButtonItem?
    
    func preferredTableHeaderView() -> MineHeaderView {
        let hv = MineHeaderView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: isSelf ? 437 : 220), isSelf: self.isSelf)
        hv.delegate = self
        return hv
    }

    func preferredPagingView() -> JXPagingView {
        return JXPagingView(delegate: self)
    }
    
    var showBackButton: Bool = false
    
    /// 分类标题名称
    private var titles: [String] {
        return ["动态"]
    }
    
    /// 请求用户的信息 （如果为空，请求的接口返回的就是自己的信息）
    private(set) public var username: String?
    /// 是否自己
    public var isSelf: Bool {
        return username == nil || username == JMSGUser.myInfo().username
    }
    init(username: String? = nil) {
        super.init()
        self.username = username
    }
    
    init(username: String? = nil, completeClosure: dismissClosure?) {
        super.init()
        self.username = username
        self.completeClosure = completeClosure
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(rounterParams params: Dictionary<String, Any>?) {
        fatalError("init(rounterParams:) has not been implemented")
    }
    
    deinit {
        removeNotifications()
    }
    
}

// MARK: ---------------------------------------- Overrides -------------------------------------------- 导航栏
extension MineViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.hidden]
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

extension MineViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (index == 0)
    }
}

extension MineViewController: JXPagingMainTableViewGestureDelegate {
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        //禁止segmentedView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
            return false
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}

// MARK: ---------------------------------------- Overrides --------------------------------------------
extension MineViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addNotifications()
        setup()
        initializeUI()
        reloadAll()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
        //reloadAll()
        requestUserInfos()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MineViewController {
    
    @objc private func dismissSelf() {
        self.dismiss(animated: true) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.completeClosure?()
        }
    }
    
    private func setup() {
    
        /// 设置个人资料、设置按钮
        
//        if isSelf {
//            let b1 = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
//            b1.setImage(UIImage(named: "icon_profile"), for: .normal)
//            b1.adjustsImageWhenHighlighted = false
//            b1.addTarget(self, action: #selector(mineViewController(didClickProfileButton:)), for: .touchUpInside)
//            let r1 = UIBarButtonItem(customView: b1)
//
//            let b2 = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
//            b2.setImage(UIImage(named: "icon_setting"), for: .normal)
//            b2.adjustsImageWhenHighlighted = false
//            b2.addTarget(self, action: #selector(mineViewController(didClickSettingButton:)), for: .touchUpInside)
//            let r2 = UIBarButtonItem(customView: b2)
//
//            let b3 = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
//            b3.setImage(UIImage(named: "vip_gray"), for: .normal)
//            b3.adjustsImageWhenHighlighted = false
//            b3.addTarget(self, action: #selector(mineViewController(didClickVipApplyButton:)), for: .touchUpInside)
//            self.vipButton = b3
//            let r3 = UIBarButtonItem(customView: b3)
//            self.vipRightBarBtn = r3
//
//            self.navigationItem.rightBarButtonItems = [r2, r1, r3]
//        } else {
//            if showBackButton == true {
//                self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_back"), style: .done, target: self, action: #selector(dismissSelf))
//            }
//        }
    }
    
    private func initializeUI() {
        view.backgroundColor = UIColor.theme.background
        dataSource.titles = titles
        dataSource.titleSelectedColor = UIColor.text.x1d1a1a
        dataSource.titleNormalColor = UIColor.text.x9b9b9b
        dataSource.isTitleColorGradientEnabled = true
        dataSource.isTitleZoomEnabled = true
        dataSource.isItemSpacingAverageEnabled = false

        segmentedView.backgroundColor = UIColor(hex: 0xf4f4f4)
        segmentedView.delegate = self
        segmentedView.isContentScrollViewClickTransitionAnimationEnabled = false
        segmentedView.dataSource = dataSource

        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorColor = UIColor.text.x1d1a1a
        indicator.indicatorWidth = 20
        indicator.indicatorHeight = 3
        indicator.verticalOffset = 5
        segmentedView.indicators = [indicator]

        pagingView.mainTableView.gestureDelegate = self
        self.view.addSubview(pagingView)
        
        segmentedView.listContainer = pagingView.listContainerView

        //扣边返回处理，下面的代码要加上
        pagingView.listContainerView.contentScrollView().panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        pagingView.mainTableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
        pagingView.mainTableView.mj_header = ViewFactory.normalHeader { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.reloadAll()
            //self.pagingView.mainTableView.mj_header?.endRefreshing()
        }
        
        pagingView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        //categoryView.contentScrollView = pagingView.listContainerView.collectionView
    }
    
}

// MARK: ---------------------------------------- 数据请求 --------------------------------------------
extension MineViewController {
    
    /// 获取用户信息
    private func requestUserInfos(group: DispatchGroup? = nil) {
        group?.enter()
        provider.rx.requestResult(.info(username)).subscribe(onNext: { [weak self] (result: Result<MineInfoResponseModel, AnyError>, isCache: Bool) in
            
            guard let weakSelf = self else {
                group?.leave()
                return
            }
            switch result {
            case let .success(response):
                
                if let code = response.code, code == 200 {
                    if let result = response.result {
                        weakSelf.infoModel = result
                        weakSelf.headerView.model = result
                        weakSelf.profileDetailController?.model = result
                    }
                } else {
                    if let msg = response.message {
                        AlertManager.presentAlertView(message: msg)
                    }
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
            group?.leave()
        }).disposed(by: disposeBag)
    }
    
}

// MARK: ---------------------------------------- 通知相关 --------------------------------------------
extension MineViewController {
    
    private func addNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(mineViewControllerShouldPresentPostController), name: GlobalNotificationName.presentPostController.name, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(reloadAll), name: GlobalNotificationName.refreshUserInfo.name, object: nil)
    }

    private func removeNotifications() {
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.presentPostController.name, object: nil)
        
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.refreshUserInfo.name, object: nil)
    }
    
}

// MARK: ------------------------------------ 跳转 ----------------------------------------
extension MineViewController {
    
    private func pushToPhotoCollectionDisplayViewController() {
        guard let list = self.infoModel?.imgList else { return }
        var models: [MinePhotoCollectionDisplayModel] = []
        for i in 0..<list.count {
            guard let m = MinePhotoCollectionDisplayModel(JSON: list[i].toJSON()) else { continue }
            m.isDisplaying = i == 0
            models.append(m)
        }
        let c = MinePhotoCollectionDisplayViewController()
        c.currentlyDisplayingModel = models.count > 0 ? models[0] : nil
        c.collectionList = models
        self.navigationController?.pushViewController(c, animated: true)
    }
    
}

// MARK: ------------------------------------ 事件方法 ----------------------------------------
@objc
extension MineViewController {
 
    /// 点击返回按钮
    private func mineViewController(didClickPopButton sender: UIBarButtonItem) {
        if navigationController?.viewControllers.count ?? 0 > 1 {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    /// 点击个人资料按钮
    private func mineViewController(didClickProfileButton sender: UIBarButtonItem) {
        let c = MineInfoViewController()
        c.model = infoModel
        self.navigationController?.pushViewController(c, animated: true)
    }
    
    /// 点击设置按钮
    private func mineViewController(didClickSettingButton sender: UIBarButtonItem) {
        let s = MTUpdatePasswordController()
        self.navigationController?.pushViewController(s, animated: true)
    }
    
    ///
    private func mineViewController(didClickVipApplyButton sender: UIBarButtonItem) {
        provider.originRequest(.vipApply, callbackQueue: nil, progress: nil) { (result, isCache) in
            switch result {
            case let .success(response):
                if let data = try? response.mapJSON() as? [String: Any], let code = data["code"] as? Int, code == 200 {
                    AlertManager.presentAlertView(message: "申请成功")
                } else {
                    AlertManager.presentAlertView(message: "申请失败")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }
    }
    
    /// 弹出相册
    private func mineViewControllerShouldPresentPostController() {
        let c = PublishViewController()
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
    /// 刷新界面
    private func reloadAll() {
        let group = DispatchGroup()
        self.publishListController?.reloadList(group: group)
        requestUserInfos(group: group)
        group.notify(queue: .main) {
            self.pagingView.mainTableView.mj_header?.endRefreshing()
        }
    }
    
}

// MARK: ---------------------------------------- 所有代理 --------------------------------------------
// MARK: ---------------------------------------- JXCategoryTitleView 代理 --------------------------------------------
extension MineViewController: JXCategoryViewDelegate {
    
    func categoryView(_ categoryView: JXCategoryBaseView!, scrollingFromLeftIndex leftIndex: Int, toRightIndex rightIndex: Int, ratio: CGFloat) {

    }
    
}

// MARK: ------------------ JXPagingView 代理 ----------------------
extension MineViewController: JXPagingViewDelegate {
    
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return isSelf ? 498 : 420
    }
    
    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        headerView
    }
    
    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return 0
    }

    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return UIView()
    }
    
    func numberOfLists(in pagingView: JXPagingView) -> Int {
        titles.count
    }

    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        let c = MinePublishListViewController()
        c.delegate = self
        self.publishListController = c
        c.username = self.username
        controllers.append(c)
        return c
    }
    
}

// MARK: ------------------------------------ MineHeaderViewDelegate ----------------------------------------
extension MineViewController: MineHeaderViewDelegate {
    
    func mineHeaderViewDidClickAddFriendButton(_ headerView: MineHeaderView) {
        if let un = self.username {
            self.presentGiftView(isFriend: false, imUserName: un, didClickRechargeCallBack: { [weak self] in
                guard let weakself = self else { return }
                if UserDefaults.AppValidate.isValidate.storedBool == false {
                    let c = MTPaymentViewController()
                    weakself.navigationController?.pushViewController(c, animated: true)
                } else {
                    let c = MTInAppPurchasesViewController()
                    weakself.navigationController?.pushViewController(c, animated: true)
                }
                }, selectedGiftCallBack: { [weak self] (model, count) in
                    
            }, didClickSayHiCallBack: { [weak self] (model, count) in
                guard let weakself = self else { return }
                let c = MTAddFriendViewController(giftCount: count, targetUserName: un, giftModel: model)
                weakself.navigationController?.pushViewController(c, animated: true)
            }) {
                
            }
        }
    }
    
    func mineHeaderViewShouldPushToPurchaseRecordController(_ headerView: MineHeaderView) {
        let c = MinePurchaseRecordViewController()
        self.navigationController?.pushViewController(c, animated: true)
    }
    
    func mineHeaderViewShouldPushToPhotoCollectionController(_ headerView: MineHeaderView) {
        pushToPhotoCollectionDisplayViewController()
    }
    
    func mineHeaderViewDidClickAmountButton(_ headerView: MineHeaderView) {
        self.navigationController?.pushViewController(MTAccountController(), animated: true)
    }
    
    func mineHeaderViewDidClickGiftButton(_ headerView: MineHeaderView) {
        self.navigationController?.pushViewController(MTGiftController(), animated: true)
    }
    
    func mineHeaderViewDidClickWithdrawButton(_ headerView: MineHeaderView) {
        user_provider.rx.requestResult(.queryWithdraw).subscribe(onNext: { [weak self] (result: Result<MineWithdrawResponseModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if response.code == 200, let model = response.result {
                    weakself.presentWithdrawAlert(with: "提现", message: "您的\(model.ticketAmount)点券将提现成\n\(model.rmbAmount)人民币，是否提现？") {
                        weakself.applyWithdraw(with: model)
                    }
                } else {
                    AlertManager.presentAlertView(message: response.message ?? "申请失败")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: disposeBag)
    }
    
    func mineHeaderViewDidClickRechargeDiamondButton(_ headerView: MineHeaderView) {
//        if let token = UserCenter.default.auth?.token {
//            Navigate.safari(url: "\(RechargeH5BaseUrl)?token=\(token)").push()
//        }
//        let c = MTPaymentViewController()
//        self.navigationController?.pushViewController(c, animated: true)
        if UserDefaults.AppValidate.isValidate.storedBool == false {
            let c = MTPaymentViewController()
            self.navigationController?.pushViewController(c, animated: true)
        } else {
            let c = MTInAppPurchasesViewController()
            self.navigationController?.pushViewController(c, animated: true)
        }
    }
    
    func mineHeaderViewDidClickExchangeDiamondButton(_ headerView: MineHeaderView) {
        queryTranslateDiamond()
    }
    
    /// 弹客服
    private func presentContactCustomerService(title: String) {
        let c = UIAlertController(title: "提示", message: title, preferredStyle: .alert)
        let a = UIAlertAction(title: "点击复制客服微信号", style: .default) { (action) in
            UIPasteboard.general.string = ""
        }
        c.addAction(a)
        self.present(c, animated: true, completion: nil)
    }
    
    /// 查询点券换钻石接口
    private func queryTranslateDiamond() {
        user_provider.rx.requestResult(.queryTranslateDiamond).subscribe(onNext: { [weak self] (result: Result<MineWithdrawResponseModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(model):
                if model.code == 200, let model = model.result {
                    if model.ticketAmount == 0 {
                        AlertManager.presentAlertView(message: "余额不足")
                        return
                    }
                    weakself.presentWithdrawAlert(with: "兑换钻石", message: "您的\(model.ticketAmount)点券将兑换成\n\(model.money)钻石，是否提现？") {

                        weakself.translateDiamond(model: model)
                    }
                } else {
                    AlertManager.presentAlertView(message: model.message ?? "申请失败")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
            break
            }
        }).disposed(by: disposeBag)
    }
    
    /// 兑换钻石
    private func translateDiamond(model: MineWithdrawModel) {
        user_provider.originRequest(.translateDiamond(model.ticketAmount), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let data = try? response.mapJSON() as? [String: Any], let code = data["code"] as? Int {
                    if code == 200 {
                        weakself.requestUserInfos()
                    } else if let msg = data["message"] as? String {
                        AlertManager.presentAlertView(message: msg)
                    } else {
                        AlertManager.presentAlertView(message: "申请失败")
                    }
                } else {
                    AlertManager.presentAlertView(message: "申请失败")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }
    }
    
    /// 弹窗询问是否提现
    private func presentWithdrawAlert(with title: String, message: String, action: @escaping ()->()) {
        let c = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let a = UIAlertAction(title: "确定", style: .default) { (_) in
            action()
        }
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        c.addAction(cancel)
        c.addAction(a)
        self.present(c, animated: true, completion: nil)
    }
    
    /// 提现申请
    private func applyWithdraw(with model: MineWithdrawModel) {
//        user_provider.originRequest(.applyWithdraw(model.ticketAmount), callbackQueue: .main, progress: nil) { [weak self] (result, isCache) in
//            guard let weakself = self else { return }
//            switch result {
//            case let .success(response):
//                if let data = try? response.mapJSON() as? [String: Any], let code = data["code"] as? Int {
//                    if code == 200 {
//                        weakself.requestUserInfos()
//                        weakself.presentContactCustomerService(title: "申请成功，请与客服联系！")
//                    } else if let msg = data["message"] as? String {
//                        AlertManager.presentAlertView(message: msg)
//                    } else {
//                        AlertManager.presentAlertView(message: "申请失败")
//                    }
//                } else {
//                    AlertManager.presentAlertView(message: "申请失败")
//                }
//                break
//                
//            case .failure(_):
//                AlertManager.presentAlertView(message: "申请失败")
//                break
//            }
//        }
    }
    
}

// MARK: ------------------------------------ MinePublishListViewControllerDelegate ----------------------------------------
extension MineViewController: MinePublishListViewControllerDelegate {
    
    func publishViewController(_ controller: MinePublishListViewController, shouldPushToPhotoCollectionControllerWithList list: [UserMediaListModel]) {
        var models: [MinePhotoCollectionDisplayModel] = []
        for i in 0..<list.count {
            guard let m = MinePhotoCollectionDisplayModel(JSON: list[i].toJSON()) else { continue }
            m.isDisplaying = i == 0
            models.append(m)
        }
        let c = MinePhotoCollectionDisplayViewController()
        c.currentlyDisplayingModel = models.count > 0 ? models[0] : nil
        c.collectionList = models
        self.navigationController?.pushViewController(c, animated: true)
    }
    
}
